import { Controller, Post, Header, Res, Get, StreamableFile,Body} from '@nestjs/common';
import { Response } from 'express';  
import { createReadStream } from 'fs';
import { join } from 'path';
import { HttpException, HttpStatus } from '@nestjs/common';

@Controller('ap/log')
export class ApLogController {   
    private logContent:any
    private startLine:number = 0;
    private endLine:number = 70;
    private logLevel:string = '0';
    @Post('/export')
    async downloadFile(@Body('id') id:any) {
        try {
            const filePath = join(process.cwd(), 'public/app.log');
            this.logContent = await new Promise<string>((resolve, reject) => {
                let data = '';
                const fileStream = createReadStream(filePath, 'utf8');                
                fileStream.on('data', chunk => {
                    data += chunk;
                });
                fileStream.on('end', () => {
                    resolve(data);
                });                
                fileStream.on('error', error => {
                    reject(error);
                });
            });
            return {
                code:200,
                data:{
                    addr:"",
                    id:id
                }
            }   
        } catch (error) {
            throw new HttpException('下载失败', HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    @Post('/whole')
    async getLog(@Res() res: Response) {
        try {
            const filePath = join(process.cwd(), 'public/app.log');
            this.logContent = await new Promise<string>((resolve, reject) => {
                let data = '';
                const fileStream = createReadStream(filePath, 'utf8');                
                fileStream.on('data', chunk => {
                    data += chunk;
                });
                fileStream.on('end', () => {
                    resolve(data);
                });                
                fileStream.on('error', error => {
                    reject(error);
                });
            });
            const contentList = this.logContent.split("\n");
            return res.json({
                code: 200,
                data:{
                  line:contentList.length
                }
            });          
        } catch (error) {
            return res.status(500).json({
                code: 500,
                
            });
        }
    }

    
    @Post('/select')
    async getSelectLog(@Body() body: any) {  
       const {line_start,line_end} = body; 
       const contentList = this.logContent.split("\n");
       const list = contentList.slice(line_start,line_end);
       return {
        code:200,
        data:{
          log:list 
        }
       }
    }
    
    public incrementCount:number = 0;
    @Post('/increment')
    async getIncrementalLog(@Body() body: any) {
       let list = this.logContent.split("\n").slice(this.startLine,this.endLine)   
       this.startLine = this.endLine;
       this.endLine = this.endLine + 70;
       this.logContent = this.logContent + list.join("\n");
       this.incrementCount++;
       if(this.incrementCount>=3){
        list = []
        this.incrementCount = 0;
       }
       return {
        code:200,
        data:{
          log:list,
          line:this.logContent.split("\n").length
        }
       }
    }


    // 清除日志
    @Post('/clear')
    async clearLog() {
        
        return {
            code:200,
            message:'清除成功'
        }
    }


    // 日志等级设置
    @Post('/log_level_set')
    async setLogLevel(@Body() body: any) {
        const {level} = body;
        this.logLevel = level;
        return {
            code:200,
            message:'日志等级设置成功'
        }
    }

    // 日志等级获取
    @Post('/log_level_get')
    async getLogLevel() {
        return {
            code:200,
            data:{
                level:this.logLevel
            }
        }
    }

    public logId = 0
    /* 导出所有日志 */
    @Post('/export_all')
    async exportAllLog(@Body() body: any) {
      const {id} = body;
      this.logId = id;
      return {
        code:200
      }
    }
  
    public logStatus = ["failed","running","idle","success"]
    public currentStatusIndex = 0
    /* 查询导出所有日志状态 */
    @Post('/export_all_state')
    async getExportAllLogStatus() {
      const currentStatus = this.logStatus[this.currentStatusIndex]
      this.currentStatusIndex++
      if(this.currentStatusIndex >= this.logStatus.length){
        this.currentStatusIndex = 0
      }
      const addr = `http://192.168.5.74:3001/public/app.log`
      return {
        code:200,
        data:{
          id:this.logId,
          status:currentStatus,
          addr:addr
        }
      }
    }
}

